package org.blogwu.learn.threadLearn.自己实现一个信号量;


import java.time.LocalDate;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class TestMain extends Thread {

    static MySemaphore semaphore = new MySemaphore(5);

    static AtomicInteger atomicInteger = new AtomicInteger(0);

    public TestMain(String name) {
        super(name);
    }

    @Override
    public void run() {
        try {
            // 获取一个进入临界区的凭证
            semaphore.acquire();

            Thread.sleep(3000);
            System.out.println(getName() + " exec time:" + LocalDate.now() + ";atomic:" + atomicInteger.get());
            if (((atomicInteger.getAndIncrement() + 1) % 5) == 0) {
                System.out.println(" ---------------- ");
            }
            Thread.sleep(300);
            semaphore.release(); // 释放一个进入临界区的凭证
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 20; i++) {
            executorService.submit(new TestMain("t" + i));
        }
    }
}
